Imports Cdm.DataCore.CaseNotes

Partial Class Case_caseDocuments
    Inherits System.Web.UI.UserControl

    Private bAnyDeletesVisible As Boolean = False

    Private Property SortExpression() As String
        Get
            If ViewState("SortExpression") Is Nothing Then
                ViewState("SortExpression") = "DateModified"
            End If
            Return ViewState("SortExpression")
        End Get
        Set(ByVal value As String)
            If value.Equals(Me.SortExpression) Then
                ToggleSortDirection()
            Else
                ViewState("SortDirection") = " ASC"
            End If
            ViewState("SortExpression") = value
        End Set
    End Property

    Private Sub ToggleSortDirection()
        If ViewState("SortDirection").Equals(" DESC") Then
            ViewState("SortDirection") = " ASC"
        Else
            ViewState("SortDirection") = " DESC"
        End If
    End Sub

    Private ReadOnly Property SortDirection() As String
        Get
            Return ViewState("SortDirection")
        End Get
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Me.IsPostBack Then
            ViewState("SortDirection") = " DESC"
            Me.PostFilePanel.Visible = UserAuthorization.HasInsertPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseDocuments)
            BindGrid()
        Else
            SetDeletesVisible()
        End If
    End Sub

    Private Sub BindGrid()
        bAnyDeletesVisible = False
        Me.DocumentsGridView.DataSource = ParticipantDocument.ListByParticipant(EntityController.GetParticipant().ParticipantId, Me.SortExpression + Me.SortDirection)
        Me.DocumentsGridView.DataBind()
        SetDeletesVisible()
    End Sub

    Private Sub SetDeletesVisible()

        Dim rowModifiedBy As String
        For iRow As Integer = 0 To DocumentsGridView.Rows.Count - 1
            rowModifiedBy = DocumentsGridView.DataKeys(iRow).Value.ToString()
            Dim deleteButton As Button = DocumentsGridView.Rows(iRow).FindControl("deleteButton")
            If Not deleteButton Is Nothing Then
                If MayDelete(rowModifiedBy) Then
                    deleteButton.Visible = True
                    bAnyDeletesVisible = True
                    deleteButton.Attributes.Add("onclick", "return confirm('Are you sure you want to remove this document from the participant file?');")
                Else
                    deleteButton.Visible = False
                End If
            End If
        Next

        SetDeleteColumnVisible()

    End Sub

    Private Sub SetDeleteColumnVisible()
        DocumentsGridView.Columns(DocumentsGridView.Columns.Count - 1).Visible = bAnyDeletesVisible
    End Sub

    Private Function MayDelete(ByVal modifiedBy As String) As Boolean
        'If the current user has delete permission, return true
        'without checking who posted the document
        If UserAuthorization.HasDeletePermssion(Cdm.DataCore.UserSecurity.Permission.PermissionType.CaseDocuments) Then
            Return True
        End If

        'If user does not have delete permission, check if current user is the one who posted
        'the document.  If so, user has right to delete.
        If modifiedBy = UserAuthorization.CurrentUser.LogonId Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetWholePath(ByVal fileName As String) As String
        Return EntityController.FullPath(ConfigurationManager.AppSettings("ParticipantDocumentLocation")) + fileName
    End Function

    Public Function ReplaceSingleTick(ByVal s As String) As String
        Return s.Replace("'", "&rsquo;")
    End Function

    Protected Sub PostButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles PostButton.Click
        Dim errorList As ArrayList
        errorList = New ArrayList
        If Me.UploadDocumentFile.PostedFile Is Nothing Then
            errorList.Add("No File has been posted.")
        Else
            If Me.UploadDocumentFile.PostedFile.FileName.Equals("") Then
                errorList.Add("No File has been posted.")
            Else
                Dim fileExtension As String = Me.UploadDocumentFile.PostedFile.FileName.Substring(Me.UploadDocumentFile.PostedFile.FileName.LastIndexOf("."))
                If IsExcludedType(fileExtension) Then
                    errorList.Add("Files with an extension of " + fileExtension + " are prohibited to be uploaded into the system.")
                End If
            End If
        End If
        If Me.DescriptionTextBox.Text = "" Then
            errorList.Add("Description is required")
        End If




        If errorList.Count > 0 Then
            Me.DocValidateError.Text = "Can not Upload Document."
            Me.DocValidateError.SetErrors(errorList)
            Me.DocValidateError.Visible = True
        Else
            Dim fileName As String = GetFileNameWithoutDirectory(Me.UploadDocumentFile.PostedFile.FileName)
            Dim filePath As String = GetFilePath(fileName)
            Me.UploadDocumentFile.PostedFile.SaveAs(filePath)
            Dim newUploadDoc As New ParticipantDocument()
            newUploadDoc.ParticipantId = CInt(Session("ParticipantId"))
            newUploadDoc.FileName = GetFileNameWithoutDirectory(filePath)
            newUploadDoc.Comments = Me.CommentsTextBox.Text
            newUploadDoc.LastModified = UserAuthorization.CurrentUser.LogonId
            newUploadDoc.DateModified = DateTime.Now
            newUploadDoc.Description = Me.DescriptionTextBox.Text
            newUploadDoc.PosterFirstName = UserAuthorization.CurrentUser.FirstName
            newUploadDoc.PosterLastName = UserAuthorization.CurrentUser.LastName
            newUploadDoc.Persist()
            'Clear the TextBoxes
            CommentsTextBox.Text = ""
            DescriptionTextBox.Text = ""
            BindGrid()
        End If
    End Sub

    ''' <summary>
    ''' Returns the virtual directory 
    ''' used when attempting to retrieve the file
    ''' </summary>
    ''' <returns>The virtual path to the file directory in the appsetting ParticipantDocumentLocation</returns>
    ''' <remarks></remarks>
    Private Function GetUploadVirtualFileDirectory() As String
        Return ConfigurationManager.AppSettings("ParticipantDocumentLocation")
    End Function

    Private Function IsExcludedType(ByVal ext As String) As Boolean
        Dim excludeList As String = Application("FileDocumentExcludeTypes")
        Dim excludeArray As String() = excludeList.Split(",")
        For i As Integer = 0 To excludeArray.Length - 1
            If ext.ToUpper().Trim().Equals(excludeArray(i).ToUpper().Trim()) Then
                Return True
            End If
        Next
        Return False
    End Function

    ''' <summary>
    ''' Returns the mapped windows directory
    ''' where the uploaded document files need to go.
    ''' </summary>
    ''' <returns>The actual windows path on the server to the directory in the
    '''          appSetting ParticipantDocumentLocation</returns>
    ''' <remarks></remarks>
    Private Function GetActualFileDirectory() As String
        Dim directory As String = Server.MapPath(GetUploadVirtualFileDirectory())
        If directory.EndsWith("\") Then
            Return directory
        Else
            Return directory & "\"
        End If
    End Function

    ''' <summary>
    ''' Returns the fileName 
    ''' </summary>
    ''' <param name="uploadedFilePath"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetFilePath(ByVal uploadedFileName As String) As String
        Dim fileNameBeforeExtension As String = ""
        Dim fileExtension As String = ""

        BreakFileIntoParts(uploadedFileName, fileNameBeforeExtension, fileExtension)

        Dim defaultFilePath As String
        Dim subscript As Integer = 0
        defaultFilePath = String.Concat(GetActualFileDirectory(), fileNameBeforeExtension, "_", Session("ParticipantId").ToString(), fileExtension)
        Dim filePath As String = defaultFilePath
        While System.IO.File.Exists(filePath)
            subscript = subscript + 1
            filePath = String.Concat(GetActualFileDirectory(), fileNameBeforeExtension, "_", Session("ParticipantId").ToString(), "_", subscript.ToString(), fileExtension)
        End While

        Return filePath

    End Function

    Private Sub BreakFileIntoParts(ByVal fileName As String, ByRef baseFileName As String, ByRef fileExtension As String)
        Dim lastPeriod As Integer = fileName.LastIndexOf(".")
        If (lastPeriod > 0) Then
            baseFileName = fileName.Substring(0, lastPeriod)
            fileExtension = fileName.Substring(lastPeriod)
        Else
            baseFileName = fileName
            fileExtension = ""
        End If
    End Sub

    Private Function GetFileNameWithoutDirectory(ByVal uploadedFilePath As String) As String
        Return uploadedFilePath.Substring(uploadedFilePath.LastIndexOf("\") + 1)
    End Function

    Protected Sub DocumentsGridView_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs) Handles DocumentsGridView.DataBinding

    End Sub

    Protected Sub DocumentsGridView_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles DocumentsGridView.PageIndexChanging
        DocumentsGridView.PageIndex = e.NewPageIndex
        BindGrid()
    End Sub


    Protected Sub DocumentsGridView_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles DocumentsGridView.RowCreated
        Try
            Dim currDoc As ParticipantDocument = CType(e.Row.DataItem, ParticipantDocument)
            If Not currDoc Is Nothing Then
                Dim deleteButton As Button = CType(e.Row.FindControl("deleteButton"), Button)
                If Not IsNothing(deleteButton) Then
                    If currDoc.LastModified.Equals(UserAuthorization.CurrentUser.LogonId) Then
                        deleteButton.Visible = True
                        deleteButton.Attributes.Add("onclick", "return confirm('Are you sure you want to remove this document from the participant file?');")
                    Else
                        deleteButton.Visible = False
                    End If
                End If
            End If
        Catch ex As Exception

        End Try


    End Sub

    Protected Sub DocumentsGridView_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles DocumentsGridView.RowDeleting
        Dim deleteButton As Button = CType(DocumentsGridView.Rows(e.RowIndex).FindControl("deleteButton"), Button)
        If Not deleteButton Is Nothing Then
            Dim Id As Integer = CInt(deleteButton.CommandArgument)
            Dim removeDoc As ParticipantDocument = ParticipantDocument.Retrieve(Id)
            Dim filePath As String = GetFilePath(removeDoc.FileName)
            If System.IO.File.Exists(filePath) Then
                System.IO.File.Delete(filePath)
            End If
            removeDoc.Remove()
            DocumentsGridView.PageIndex = 0
            BindGrid()
        End If
    End Sub

    Protected Sub DocumentsGridView_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles DocumentsGridView.Sorted
        BindGrid()
    End Sub

    Protected Sub DocumentsGridView_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles DocumentsGridView.Sorting
        Me.SortExpression = e.SortExpression
    End Sub
End Class
